import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, Form, Input, message, Radio, Row, Select, Table} from 'antd';
import MessageDetail from '../../components/common/messageDetail';
import Constants from "../../utils/Constants";

const R = require('ramda');


const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const messageCenter = Form.create()(class messageCenter extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tempSelectMsgKeys: [],
            tempSelectMsg: []
        }
    }

    componentDidMount() {
        this.props.dispatch({
            type: 'messageCenter/queryMessages',
            payload: {
                page: Constants.DEFAULT_PAGE
            }
        });
        this.props.dispatch({ type: 'messageCenter/getUnReadCount', payload: {} });
    }

    handleViewMessage = (record) => {
        this.props.dispatch({
            type: 'messageCenter/getMsgById',
            payload: {
                id: record.id,
                onSuccess: () => {
                    this.props.dispatch({
                        type: 'messageCenter/updateMsgReady',
                        payload: {
                            id: record.id,
                            onSuccess: record.isready === "0" ? () => {
                                this.props.dispatch({
                                    type: 'messageCenter/refreshState',
                                    payload: {
                                        unReadCount: this.props.messageCenter.unReadCount - 1
                                    }
                                });
                            } : null
                        }
                    });
                }
            }
        });
        this.refs.MessageDetail.handleOpen();
    }

    handleSearch = (event, flag, again) => {
        let values = this.props.form.getFieldsValue();
        let newPage = this.props.messageCenter.page;
        newPage.page = flag ? newPage.page : 1;
        this.props.dispatch({
            type: 'messageCenter/queryMessages',
            payload: {
                ...values,
                page: newPage,
                onSuccess: again ? (list) => {
                    if (R.isEmpty(list) && newPage.page > 1) {
                        newPage.page = newPage.page - 1;
                        this.props.dispatch({
                            type: 'messageCenter/queryMessages',
                            payload: {
                                ...values,
                                page: newPage
                            }
                        })
                    }
                } : null
            }
        });
    };

    handleDelete = (record) => {
        this.props.dispatch({
            type: 'messageCenter/deleteMsgById',
            payload: {
                id: record.id,
                onSuccess: () => {
                    this.props.dispatch({ type: 'messageCenter/getUnReadCount' });
                    this.handleSearch(null, true, true);
                }
            }
        });
    };

    handleBatchDelete = () => {
        if (R.isNil(this.state.tempSelectMsgKeys) || R.isEmpty(this.state.tempSelectMsgKeys)) {
            message.info("亲，先选一个！");
            return;
        }
        this.props.dispatch({
            type: 'messageCenter/deleteMsgs',
            payload: {
                ids: this.state.tempSelectMsgKeys,
                onSuccess: () => {
                    this.setState({ tempSelectMsgKeys: [], tempSelectMsg: [] });
                    this.props.dispatch({ type: 'messageCenter/getUnReadCount' });
                    this.handleSearch(null, true, true);
                }
            }
        });
    };

    columns = [
        {
            title: '来源', dataIndex: 'sender', key: 'sender',
            render: (text, record, index) => {
                return <span style={{ fontWeight: record.isready === "1" ? '' : 'bold' }}>{"System"}</span>
            }
        },
        {
            title: '产生时间', dataIndex: 'rectime', key: 'rectime',
            render: (text, record, index) => {
                return <span style={{ fontWeight: record.isready === "1" ? '' : 'bold' }}>{record.rectime}</span>
            }
        },
        {
            title: '所属模块', dataIndex: 'type', key: 'type',
            render: (text, record, index) => {
                return <span style={{ fontWeight: record.isready === "1" ? '' : 'bold' }}>{Constants.MESSAGE_MODULE[record.type]}</span>
            }
        },
        {
            title: '概述', dataIndex: 'title', key: 'title',
            render: (text, record, index) => {
                return <span style={{ fontWeight: record.isready === "1" ? '' : 'bold' }}>{record.title}</span>
            }
        },
        {
            title: '操作', key: 'key_oprator',
            render: (text, record, index) => {
                return (
                    <div>
                        <a href="#" onClick={this.handleViewMessage.bind(this, record)}>查看</a>
                        <span className="ant-divider" />
                        <a href="#" onClick={this.handleDelete.bind(this, record)}>删除</a>
                    </div>
                )
            }
        }];

    render() {
        let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 4 } };
        const { getFieldDecorator } = this.props.form;
        let values = this.props.form.getFieldsValue();
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.messageCenter.page.size,
            total: this.props.messageCenter.page.totalRow,
            showSizeChanger: true,
            current: this.props.messageCenter.page.page,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.messageCenter.page;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'messageCenter/queryMessages',
                    payload: {
                        isReady: values.isReady,
                        page: newPage,
                        type: values.type,
                        title: values.title
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                this.setState({
                    tempSelectMsgKeys: [],
                    tempSelectMsg: []
                })
                let newPage = this.props.messageCenter.page;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'messageCenter/queryMessages',
                    payload: {
                        isReady: values.isReady,
                        page: newPage,
                        type: values.type,
                        title: values.title
                    }
                });
            }
        }

        let rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    tempSelectMsgKeys: selectedRowKeys,
                    tempSelectMsg: selectedRows
                })
            },
            selectedRowKeys: this.state.tempSelectMsgKeys
        };

        return (
            <div>
                <Row>
                    <Col span={2}><FormItem {...{ labelCol: { span: 15 }, wrapperCol: { span: 5 } }} label={'新消息'}>
                        <div style={{ color: 'red' }}>{this.props.messageCenter.unReadCount > 99 ? '99+' : this.props.messageCenter.unReadCount}</div>
                    </FormItem></Col>
                    <Col span={4}><FormItem {...{ labelCol: { span: 7 }, wrapperCol: { span: 12 } }} label={'类型'}>{getFieldDecorator('isReady')(
                        <Select style={{ width: '100%' }} allowClear>
                            <Option value="1" key="1">已读</Option>
                            <Option value="0" key="0">未读</Option>
                        </Select>
                    )}</FormItem></Col>
                    <Col span={6}><FormItem {...{ labelCol: { span: 8 }, wrapperCol: { span: 12 } }} label={'所属模块'}>{getFieldDecorator('type')(
                        <Select style={{ width: '100%' }} allowClear>
                            <Option value="customer" key="customer">客户</Option>
                            <Option value="product" key="product">产品</Option>
                            <Option value="drawer" key="drawer">开票人</Option>
                            <Option value="order" key="order">订单</Option>
                            <Option value="statement" key="statement">付款</Option>
                            <Option value="agreement" key="agreement">业务合同</Option>
                        </Select>
                    )}</FormItem></Col>
                    <Col span={5}><FormItem {...{ labelCol: { span: 5 }, wrapperCol: { span: 17 } }} label={'标题'}>{getFieldDecorator('title')(
                        <Input />
                    )}</FormItem></Col>
                    <Col span={2}>
                        <Button type="primary" icon="search" onClick={this.handleSearch.bind(this)}>查询</Button>
                    </Col>
                    <Col span={1}>
                        <Button type="primary" icon="delete" onClick={this.handleBatchDelete.bind(this)}>批量删除</Button>
                    </Col>
                </Row>
                <Table loading={this.props.loading} rowKey={record => record.id} dataSource={this.props.messageCenter.list} columns={this.columns} bordered={true} size={'middle'} rowSelection={rowSelection} pagination={pagination} />
                <MessageDetail ref="MessageDetail" dataSource={this.props.messageCenter.messageDetail} refreshList={this.handleSearch} />
            </div>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.messageCenter, messageCenter: state.messageCenter
    };
}

export default connect(mapStateToProps)(messageCenter);